package lsy.tools;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(urlPatterns = {"/*"},initParams = {
        @WebInitParam(name = "exclude",value = "/login.jsp,/login,/noprivilige.jsp,/validateCode,.css,.png,.jpg,.js")
})
public class AuthFilter implements Filter {

    public static String excludeString;

    public void init(FilterConfig filterConfig) throws ServletException{
        excludeString=filterConfig.getInitParameter("exclude");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        HttpServletResponse httpServletResponse=(HttpServletResponse) response;
        Object user=httpServletRequest.getSession().getAttribute("user");
        String uri=httpServletRequest.getRequestURI();
        if (isExist(uri)||uri.equals(httpServletRequest.getContextPath()+"/")){
            chain.doFilter(httpServletRequest,httpServletResponse);
        }else {
            if (user!=null){
                chain.doFilter(httpServletRequest,httpServletResponse);
            }else {
                httpServletResponse.sendRedirect("noprivilige.jsp");
            }
        }

    }

    public static boolean isExist(String uri){
        //最后url结尾与exclude匹配
        String[] arr=excludeString.split(",");
        boolean flag = false;
        for (String string:arr){
            if (uri.endsWith(string)){
                flag = true;
            }
        }
        return flag;
    }
}